package com.share.sharedevice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.security.utils.SecurityUtils;
import com.share.sharedevice.entity.PowerBank;
import com.share.sharedevice.mapper.PowerBankMapper;
import com.share.sharedevice.service.IPowerBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {

    @Autowired
    private PowerBankMapper powerBankMapper;

    /**
     * 获取充电宝列表
     */
    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank) {
        return powerBankMapper.selectPowerBankList(powerBank);
    }

    /**
     * 根据ID获取详细信息
     * @param id
     * @return
     */
    @Override
    public PowerBank getPowerBankById(Long id) {

        PowerBank powerBank = powerBankMapper.getPowerBankById(id);
        return powerBank;
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Long> ids) {
        powerBankMapper.deleteByIds(ids);
    }

    /**
     * 添加
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(PowerBank powerBank) {

        powerBank.setCreateBy(SecurityUtils.getUsername());

        powerBank.setUpdateBy(SecurityUtils.getUsername());

        powerBank.setCreateTime(new Date());
        powerBank.setUpdateTime(new Date());

        String powerBankNo = powerBank.getPowerBankNo();

        powerBank.setDelFlag("0");

        powerBank.setStatus("1");

        if (powerBankNo == null || "".equals(powerBankNo)){
            throw new RuntimeException("充电宝编号不能为空");
        } else if(powerBankNo != null && powerBankNo.length() > 0){
            PowerBank powerBankByPowerBankNo = powerBankMapper.getPowerBankByPowerBankNo(powerBankNo);
            if (powerBankByPowerBankNo != null) {
                throw new RuntimeException("充电宝编号已存在");
            }
        }

        powerBankMapper.add(powerBank);
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePowerBank(PowerBank powerBank) {


        Long id = powerBank.getId();

        powerBank.setUpdateBy(SecurityUtils.getUsername());

        if (id == null || id <= 0){
            throw new RuntimeException("id不能为空");
        }

        powerBank.setUpdateTime(new Date());

        String powerBankNo = powerBank.getPowerBankNo();

        if(powerBankNo == null || "".equals(powerBankNo)){
            throw new RuntimeException("充电宝编号不能为空");
        }

        powerBankMapper.updatePowerBank(powerBank);
    }


}
